define([
    "dojo/_base/kernel",
    "dojo/_base/lang",
    "dojo/dom",
    "dijit/dijit",
    "dojo/_base/declare",
    "spring/DefaultEquals"
], function(dojo,lang,dom,dijit,declare,Equals) {
	
	return declare("Spring.ValidateAllDecoration", [Spring.AbstractValidateAllDecoration, Equals], {
		constructor : function(config) {
			this.originalHandler = null;
			this.connection = null;
			lang.mixin(this, config);
		},
		
		apply : function() {
			var element = dom.byId(this.elementId);
			if (!element) {
				console.error("Could not apply ValidateAll decoration.  Element with id '" + this.elementId + "' not found in the DOM.");
			} else {
				this.originalHandler = element[this.event];
				var context = this;
				element[this.event] = function(event){
					context.handleEvent(event, context);
				};
			}
			return this;
		},
		
		cleanup : function(){
			dojo.disconnect(this.connection);
		},
		
		handleEvent : function(event, context){ 
			if (!Spring.validateAll()) {
				dojo.publish(this.elementId+"/validation", [false]);
				dojo.stopEvent(event);
			} else {
				dojo.publish(this.elementId+"/validation", [true]);
				if(dojo.isFunction(context.originalHandler)) {
					var result = context.originalHandler(event);
					if (result == false) {
						dojo.stopEvent(event);
					}
				}
			}
		}
	});
	
});